import { checkPoolHealth, restartPool } from './config'

// 连接池健康检查器
export class DatabaseHealthChecker {
  private static instance: DatabaseHealthChecker
  private isChecking = false
  private consecutiveFailures = 0
  private readonly maxConsecutiveFailures = 3
  private readonly checkInterval = 30000 // 30秒检查一次

  private constructor() {
    this.startHealthCheck()
  }

  static getInstance(): DatabaseHealthChecker {
    if (!DatabaseHealthChecker.instance) {
      DatabaseHealthChecker.instance = new DatabaseHealthChecker()
    }
    return DatabaseHealthChecker.instance
  }

  private async startHealthCheck(): Promise<void> {
    setInterval(async () => {
      await this.performHealthCheck()
    }, this.checkInterval)
  }

  private async performHealthCheck(): Promise<void> {
    if (this.isChecking) return

    this.isChecking = true
    try {
      const isHealthy = await checkPoolHealth()

      if (isHealthy) {
        this.consecutiveFailures = 0
        // console.log('✅ 数据库连接池健康状态正常')
      } else {
        this.consecutiveFailures++
        console.warn(`❌ 数据库连接池健康检查失败 (${this.consecutiveFailures}/${this.maxConsecutiveFailures})`)

        // 如果连续失败次数达到阈值，尝试重启连接池
        if (this.consecutiveFailures >= this.maxConsecutiveFailures) {
          console.log('🔄 连续健康检查失败，尝试重启连接池...')
          await this.restartPoolWithRetry()
          this.consecutiveFailures = 0
        }
      }
    } catch (error) {
      console.error('健康检查过程中发生错误:', error)
      this.consecutiveFailures++
    } finally {
      this.isChecking = false
    }
  }

  private async restartPoolWithRetry(): Promise<void> {
    const maxRetries = 3
    for (let attempt = 1; attempt <= maxRetries; attempt++) {
      try {
        console.log(`🔄 尝试重启连接池 (第 ${attempt} 次)...`)
        await restartPool()
        console.log('✅ 连接池重启成功')
        return
      } catch (error) {
        console.error(`❌ 连接池重启失败 (第 ${attempt} 次):`, error)
        if (attempt < maxRetries) {
          await new Promise(resolve => setTimeout(resolve, 5000)) // 等待5秒后重试
        }
      }
    }
    console.error('❌ 连接池重启失败，已达到最大重试次数')
  }

  // 手动触发健康检查
  async manualHealthCheck(): Promise<boolean> {
    return await checkPoolHealth()
  }

  // 手动重启连接池
  async manualRestart(): Promise<void> {
    await this.restartPoolWithRetry()
  }

  // 获取当前健康状态
  getHealthStatus(): { isHealthy: boolean; consecutiveFailures: number } {
    return {
      isHealthy: this.consecutiveFailures === 0,
      consecutiveFailures: this.consecutiveFailures
    }
  }
}

// 导出单例实例
export const databaseHealthChecker = DatabaseHealthChecker.getInstance()

// 启动健康检查（在应用启动时调用）
export function startDatabaseHealthMonitoring(): void {
  console.log('🔍 启动数据库健康监控...')
  DatabaseHealthChecker.getInstance()
}